package mysql

import (
	"crypto/md5"
	"encoding/hex"
	"web_app/models"

	"github.com/jinzhu/gorm"
)

//md5 加密的密钥
const secret = "www.baidu.com"

//向 数据库插入一条新的用户记录
func InsertUser(user *models.User) (err error) {
	//对密码进行加密
	user.Password = encryptPassword(user.Password)
	err = db.Create(user).Error
	return err
}

//查看用户名是否已存在
func CheckUserExistByUsername(username string) (err error) {
	var user []models.User
	var count int64
	//查询users表中 username字段 = 指定参数 的记录数
	err = db.Table("users").Where("username = ?", username).Find(&user).Count(&count).Error
	//err = db.Where(map[string]interface{}{"username": username, "deleted_at": &time.Time{}}).Find(&user).Count(&count).Error

	if err != nil {
		return err
	}
	if count > 0 {
		return ErrorUserExist
	}
	return
}

//密码加密md5算法
func encryptPassword(oPassword string) string {
	h := md5.New()
	h.Write([]byte(secret))
	return hex.EncodeToString(h.Sum([]byte(oPassword)))
}

//查询users表所有记录
//func SelectUser() {
//	var user []models.User
//	db.Table("users").Find(&user)
//	for _, u := range user {
//		fmt.Println(u)
//	}
//}

//用户登录时 查询用户是否存在
func CheckUserExist(user *models.User) (err error) {
	password := encryptPassword(user.Password)
	err = db.Table("users").Where(map[string]interface{}{"username": user.Username, "password": password}).Find(&user).Error
	if gorm.IsRecordNotFoundError(err) {
		return ErrorUserNotExist
	}
	if err != nil {
		//fmt.Println(err)
		return err
	}
	if password != user.Password {
		return ErrorInvalidPassword
	}

	return
}

//根据id获取用户信息
func GetUserById(id uint64) (user *models.User, err error) {
	user = new(models.User)
	err = db.Table("users").Select([]string{"user_id", "username"}).
		Where("user_id = ?", id).Find(user).Error
	//fmt.Printf("%v\n", user)
	if gorm.IsRecordNotFoundError(err) {
		err = ErrorUserNotExist
	}
	return

}
